package com.cqyc.shop.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cqyc.shop.comm.StringUtil;
import com.cqyc.shop.domain.Orders;
import com.cqyc.shop.domain.Shop;
import com.cqyc.shop.domain.User;
import com.cqyc.shop.services.OrdersServices;

@WebServlet(urlPatterns="/orders.do")
public class OrdersServlet extends HttpServlet{
	private static final long serialVersionUID = -1885867723258532390L;
	private Logger logger = LoggerFactory.getLogger(getClass());
	private SimpleDateFormat  df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private OrdersServices  ordersServices =  new  OrdersServices();
 	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.debug("订单表演正式开始");
		try {
			//1:从前台获取参数
			String num = request.getParameter("num2");
			Integer num2 = Integer.valueOf(num);
			
			BigDecimal num3 = new BigDecimal(num);
			String ordercode = StringUtil.generateUUID();
			logger.debug("{}",num2);
			HttpSession session = request.getSession();
			Object shop2 = session.getAttribute("shop2");
			Object ouser = session.getAttribute("user");
			User user = (User)ouser;
			Shop shop = (Shop)shop2;
			Orders orders = new Orders();
			orders.setUsercode(user.getUsercode());
			orders.setShopname(shop.getShopname());
			orders.setOrdercode(ordercode);
			orders.setCartinfo(shop.getShopinfo());
			orders.setPrice(shop.getPrice().multiply(num3));
			orders.setBuytotal(shop.getShoptotal());
			orders.setOrderimg(shop.getShopimg());
			orders.setHowmany(num2);
			//2:数据转换
			orders.setShoptime(df.format(new Date()));
			//3:数据校验
			//4:业务处理
			ordersServices.save(orders);
			//5:跳转
			response.sendRedirect(request.getContextPath()+"/orderslist.do");
			logger.debug("订单显示表演结束");
		} catch (Exception e) {
			logger.error("{}",e.getMessage());
			request.setAttribute("error1", e.getMessage());
			request.getRequestDispatcher("/Adminadd.jsp").forward(request, response);
		}
		
	}
}
